import { accountUserInfo } from '@/api/login'
import { hideLoading, msg } from '@/utils/tools'
import store from '@/store'
import { SET_TOKEN, SET_USER_INFO } from '@/store/types'
import { syncData, uploadUserInfo } from '@/api/auth'
import { TOKEN, TOKEN_EXPIRATIONTIME, USER_INFO } from '@/utils/storageTypes'
import { getInitInfo } from '@/api/user'
// 获取账号系统用户信息 重组 微信用户信息
export const getUserInfoFromAccountSys = async (
  tgt: string,
  authCode?: string
) => {
  const userInfo = store.state.user.userInfo
  try {
    const { data, code, msg: message } = await accountUserInfo(tgt)
    if (code !== 200) {
      msg('用户信息获取失败:' + message)
      return false
    }
    uni.setStorageSync('userInfo', { ...userInfo, ...data })
    store.commit(`user/${SET_USER_INFO}`, { ...userInfo, ...data })
    // bindAccountSys()
    await upload({
      tgt: uni.getStorageSync('threePartLoginData')?.tgt || '',
      aid: uni.getStorageSync(USER_INFO)?.aid || '',
      userDTO: uni.getStorageSync(USER_INFO) || '',
      openId: uni.getStorageSync('openId') || ''
      // code: result.code,
    })
    // 关联数据
    await syncData()
    hideLoading()
    uni.navigateBack({})
  } catch (e) {
    hideLoading()
    msg('用户信息获取失败，请稍后重试')
    console.log('用户信息获取失败', e)
    return false
  }
  return true
}

const upload = async (data: {
  aid: string
  tgt: string
  userDTO: AnyObject | '',
  openId: string
  // code: string
}) => {
  try {
    const uploadUser = await uploadUserInfo(data)
    if(uploadUser.code == 200){
      uni.setStorageSync(TOKEN,uploadUser.data.token)
      uni.setStorageSync(TOKEN_EXPIRATIONTIME,uploadUser.data.expirationTime)
      store.commit(`user/${SET_TOKEN}`,uploadUser.data.token)

      const userInfos = JSON.parse(JSON.stringify(store.state.user.userInfo))
      userInfos.avatarUrl = uploadUser.data.avatar || userInfos.avatarUrl
      userInfos.nickName = uploadUser.data.nickName || userInfos.nickName
      userInfos.username = uploadUser.data.username || userInfos.username
      uni.setStorageSync('userInfo', userInfos)
      store.commit(`user/${SET_USER_INFO}`, userInfos)
    }else{
      msg('登录失败，请关闭小程序后重新登录')
      return  false
    }
  } catch (e) {
    msg('登录失败，请关闭小程序后重新登录')
    //TODO handle the exception
  }
  return Promise.resolve()
}
